package com.WOWTradeNews.DataBase;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;


public class NewsDataBase extends SQLiteOpenHelper {

	public final static String NEWS_DATABASE_NAME = "trade_news.sqlite";
	public final static String DATABASE_PATH = "/data/data/com.WOWTradeNewsTest/databases/";
	public final static String DATABASE_TEMP_FILE_PATH = "/data/data/com.WOWTradeNewsTest/";
	public final static int DATABASE_VERSION = 1;

	private SQLiteDatabase myDataBase;
	private Context myContext;

	public static NewsDataBase currentInstance;
	
	public NewsDataBase(Context context) {
		super(context, NEWS_DATABASE_NAME, null, DATABASE_VERSION);
		this.myContext = context;
		currentInstance = this;
	}

	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();

		if (dbExist) {
			// do nothing - database already exist
		} else {
			this.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database");
			}
		}
	}

	private boolean checkDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DATABASE_PATH + NEWS_DATABASE_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
		} catch (SQLiteException e) {
			e.getStackTrace();
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	private void copyDataBase() throws IOException {
		InputStream myInput = myContext.getAssets().open(NEWS_DATABASE_NAME);
		String outFileName = DATABASE_PATH + NEWS_DATABASE_NAME;
		OutputStream myOutput = new FileOutputStream(outFileName);
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}

		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	public void openDataBase() throws SQLException {
		String myPath = DATABASE_PATH + NEWS_DATABASE_NAME;
		myDataBase = SQLiteDatabase.openDatabase(myPath, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);
	}

	@Override
	public synchronized void close() {
		if (myDataBase != null)
			myDataBase.close();
		super.close();
	}

	@Override
	public void onCreate(SQLiteDatabase db) {

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

	public Cursor selectVersionCode() {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery(" select * from system ",null);
		return cursor;
	}
	
	
	public Cursor selectNews(String type) {
		SQLiteDatabase db = this.getReadableDatabase();
		String SQL = " select * from tbl_trade_news where intType = ? order by dtStartDate desc, _id desc";
		Cursor cursor = db.rawQuery(SQL,new String[]{type});
		return cursor;
	}
	
	public Cursor selectByNewsID(String _id){
		SQLiteDatabase db = this.getReadableDatabase();
		String SQL= " select * from tbl_trade_news where _id = ? ";
		Cursor cursor = db.rawQuery(SQL,new String[] { _id });
		return cursor;		
	}
	
	public News findByNews(String _id){
		News news=new News();
		SQLiteDatabase db = this.getReadableDatabase();
		String SQL= " select * from tbl_trade_news where _id = ? ";
		Cursor cursor = db.rawQuery(SQL,new String[] { _id });		
        try{
			if(cursor.moveToNext()){
				/*news.setPK_ID(cursor.getString(cursor.getColumnIndex("_id")));
				news.setTitle(cursor.getString(cursor.getColumnIndex("vchTitle")));
				news.setSummary(cursor.getString(cursor.getColumnIndex("vchSummary")));
				news.setContent(cursor.getString(cursor.getColumnIndex("vchContent")));
				news.setType(cursor.getString(cursor.getColumnIndex("intType")));
				news.setStartDate(cursor.getString(cursor.getColumnIndex("dtStartDate")));
				news.setEndDate(cursor.getString(cursor.getColumnIndex("dtEndDate")));
				news.setImageUrl(cursor.getString(cursor.getColumnIndex("vchImageUrl")));
				news.setAttachmentUrl(cursor.getString(cursor.getColumnIndex("vchAttachmentUrl")));
				news.setContent2(cursor.getString(cursor.getColumnIndex("vchContent2")));
				news.setSource(cursor.getString(cursor.getColumnIndex("vchSource")));*/
			}
        }
        catch(Exception e){
        	Log.e("findByNews", e.toString());
        }		
        finally{
        	if(!cursor.isClosed()) cursor.close();
        	db.close();
        }
		
		return news;		
	}
}
